package com.quectel.taskserver.job.grid;

import cn.hutool.core.date.DateTime;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.grid.dto.GridEventRecordDto;
import com.quectel.core.module.grid.dto.GridEventRecordLogDto;
import com.quectel.core.module.grid.service.GridEventRecordService;
import com.quectel.util.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/2/24 17:00
 * @description new java file header...
 */
@Component
@Slf4j
public class GridEventRecordTask implements SimpleJob {

    @DubboReference
    private GridEventRecordService gridEventRecordService;


    @Override
    public void execute(ShardingContext shardingContext) {
        //查询超时事件

        Map<String, Object> params = new HashMap<>();
        params.put(GridConstant.EVENT_DEADLINE, DateUtils.format(DateTime.now(), DateUtils.FormatType.COMMON));
        List<Byte> statuses = new ArrayList<>();
        statuses.add(GridConstant.GridEventRecordStatus.TO_BE_PROCESSED.getStatus());
        statuses.add(GridConstant.GridEventRecordStatus.REJECTED.getStatus());
        params.put(SystemConstants.STATUSES, statuses);
        List<GridEventRecordDto> gridEventRecordDtos = gridEventRecordService.queryList(params);
        if (CollectionUtils.isEmpty(gridEventRecordDtos)) {
            return;
        }

        for (GridEventRecordDto gridEventRecordDto : gridEventRecordDtos) {
            gridEventRecordDto.setStatus(GridConstant.GridEventRecordStatus.EXPIRED.getStatus());

            //生成日志
            List<GridEventRecordLogDto> logs = new ArrayList<>();

            //生成日志
            GridEventRecordLogDto createLog = new GridEventRecordLogDto();
            createLog.setHandleStatus(GridConstant.GridEventRecordLogType.EXPIRED.getStatus());
            createLog.setHandleUnitName("系统");
            createLog.setHandleUserType(GridConstant.GridEventRecordPersonType.SYS.getType());
            createLog.setHandleDesc("由\"系统\"修改为已逾期");
            createLog.setCreateTime(DateTime.now());
            logs.add(createLog);

            gridEventRecordDto.setLogList(logs);

            gridEventRecordService.saveOrUpdateWithLog(gridEventRecordDto);

        }

    }
}
